#! /usr/bin/env python
# -*- coding: utf-8 -*-

from tornado import web, ioloop
import time, json, argparse, sys, os
from datetime import datetime
from wechat_alert.alert_message import prometheus_alert


class PrometheusCallbackHandler(web.RequestHandler):

    def post(self):
        try:
            print ("alertdata", self.request.body)
            payload = eval(self.request.body)
        except json.decoder.JSONDecodeError:
            raise web.HTTPError(400)
        # 获取告警级别
        level = payload['commonLabels']['level']
        # 货期告警名称
        alertname = payload['commonLabels']['alertname']
        # 告警服务类型
        service = payload['commonLabels']['service']
        try:
            sms = payload['commonLabels']['sms']  # true or false,是否短信告警
        except:
            sms = 'false'
        try:
            group = payload['commonLabels']['group']
        except:
            group = 'test'
        try:
            namespace = payload['commonLabels']['namespace']
        except:
            namespace = "Monitor"

        # 获取告警信息，列表
        alert_row = payload['alerts']
        description = ""
        summary = "Monitor告警信息"
        try:
            if payload['status'] != "resolved":
                if len(alert_row) < 2:
                    description = alert_row[0]['annotations']['description']
                    summary = '[ `告警` ]' + alert_row[0]['annotations']['summary']
                else:
                    for alert in alert_row:
                        description += alert['annotations']['description'] + '\n'
                        summary = '[`基础聚合`]' + alert_row[0]['annotations']['summary']
            else:
                if len(alert_row) < 2:
                    description = alert_row[0]['annotations']['description']
                    summary = '[<font color="info"> 恢复 </font>]' + alert_row[0]['annotations']['summary']
                else:
                    for alert in alert_row:
                        description += alert['annotations']['description'] + '\n'
                        summary = '[<font color="info"> 恢复 </font>]' + alert_row[0]['annotations']['summary']
        except:
            pass

        data = {
            'type': "prometheus",
            'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            '@timestamp': int(time.time()),
            'level': level,
            'alertname': alertname,
            'description': description,
            'summary': summary,
            'service': service,
            'group': group,
            'namespace': namespace,
            'status': payload['status']
        }
        print("prom-format-data:", json.dumps(data, ensure_ascii=False))
        prometheus_alert(data)


def make_app():
    return web.Application([
        (r"/alert/prometheus", PrometheusCallbackHandler)
    ])


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, help='监听端口', default=8088)
    parser.add_argument('--host', type=str, help='监听地址', default="0.0.0.0")
    args = parser.parse_args()
    app = make_app()
    app.listen(port=args.port, address=args.host)
    print("start app on 8088")
    ioloop.IOLoop.current().start()
